package cn.ecut.tbjie.service;

import cn.ecut.tbjie.dao.PeopleDao;
import cn.ecut.tbjie.model.People;
import cn.ecut.tbjie.model.Tokens;
import cn.ecut.tbjie.utils.TokenUtil;
import cn.ecut.tbjie.dao.TokensDao;
import org.apache.ibatis.ognl.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;


@Service
public class TokensService {

private final long ADDTIME = 1000*60*60*24*3;

@Autowired(required = false)
private TokensDao dao;


    public Tokens saveToken(String salt, Integer peopleId){

        long time = new Date().getTime();
        String timeStr = String.valueOf(time);
        String token = new TokenUtil(salt).getToken(timeStr);
        String endTime = String.valueOf(time + ADDTIME);
        Tokens tokens = new Tokens();
        tokens.setTokensEndday(endTime);
        tokens.setTokensPid(peopleId);
        tokens.setTokensTime(timeStr);
        tokens.setTokensValue(token);
        dao.insert(tokens);
        return tokens;
    }


    /**
     * 验证token
     *
     * @param tokensValue 请求中的token
     * @return -1:token已失效
     * 0：token 无法匹配
     * 1：token 验证成功
     * -1：token 超时
     * -2: token 与 id 不匹配
     */
    public int verificationToken(String tokensValue,String id) {
        System.out.println(tokensValue);
        System.out.println(dao);
        Tokens tokens = dao.findTokenByToken(tokensValue);
        long time = new Date().getTime();
        if (!Objects.nonNull(tokens)) {
            return 0;
        } else if (time >= Long.parseLong(tokens.getTokensEndday())) {
            dao.deleteByPrimaryKey(tokens.getTokensId());
            return -1;
        } else if (!String.valueOf(tokens.getTokensPid()).equals(id)) {
            return -2;
        } else {
            return 1;
        }
    }
}
